﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using myTwitter.BO;
using myTwitter.API;
using myTwitter.Model;
using myTwitter.CustomControls;
using myTwitter.DataTemplateSelectors;
using System.Diagnostics;
using myTwitter.Sorting;
using System.Text.RegularExpressions;
using System.ComponentModel;
using myTwitter.BO.Search;
using myBoard.Framework;
using myBoard.Framework.BO;
using myBoard.Framework.Controls.Navigation;
using myBoard.ExternalAPI.Google.Translate;

namespace myTwitter.CustomControls
{
    public enum EditorModes
    {
        Unknown, Reply, DirectMessage, ReTweet
    }

	public partial class IMessagesControl
	{
        private Storyboard _expandActionsSB;
        private Storyboard _collapseActionsSB;
        private Storyboard _expandAllSB;
        private Storyboard _collapseAllSB;
        private Storyboard _showMessagesSB;
        private Storyboard _hideMessagesSB;
        private Storyboard _showUserDetailsSB;
        private FrameworkElement _lastExpandedMessageControl;
        private IMessage _lastExpandedMessage;
        private EditorModes _currentMode;
        private bool _ignoreTextChanged;
        public bool IsInLoadingMode { get; set; }
        public delegate void UserInfoRequestedHangler(object sender, User user);
        public event UserInfoRequestedHangler UserInfoRequested;
        private Storyboard _loadingOnSB;
        private Storyboard _loadingOffSB;

        public IMessagesControl()
		{
            this.InitializeComponent();
            _loadingOnSB = this.Resources["LoadingOn"] as Storyboard;
            _loadingOffSB = this.Resources["LoadingOff"] as Storyboard;
            _currentMode = EditorModes.Unknown;
            //GlobalController.Views.IMessagesControl = this;
            _showMessagesSB = this.Resources["ShowMessages"] as Storyboard;
            _hideMessagesSB = this.Resources["HideMessages"] as Storyboard;
            _showUserDetailsSB = this.Resources["ShowUserDetails"] as Storyboard;            
		}

        /// <summary>
        /// Slides to the user detail view
        /// </summary>
        public void ShowUserDetails(User user)
        {
            Singletons singletons = new Singletons(); 
            singletons.Twitter.SelectedUserInfo = user;

            /*if (GlobalController.Views.IMessagesControl != null)
                GlobalController.Views.IMessagesControl.BeginStoryboard(_showUserDetailsSB); */
        }

        void _detailsBt_Click(object sender, RoutedEventArgs e)
        {
            this.BeginStoryboard(_showMessagesSB);
        }

        public void LoadingOn()
        {
            this.BeginStoryboard(_loadingOnSB);
            _preLoader.Start();
        }

        public void LoadingOff()
        {
            this.BeginStoryboard(_loadingOffSB);
            _preLoader.Stop();
        }

		private void _replyBt_Click(object sender, System.Windows.RoutedEventArgs e)
		{
            FrameworkElement fe = sender as FrameworkElement;
            TextBox tbx = fe.FindName("_textMsg") as TextBox;
            tbx.Focus();
            
            if (string.IsNullOrEmpty(tbx.Text))
            {
                tbx.Text = string.Format("@{0} ", ((IMessage)fe.DataContext).User.ScreenName);
            }

            tbx.SelectionStart = tbx.Text.Length;
            _currentMode = EditorModes.Reply;
            ExpandEditor(sender);
		}

        private void _dmBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            FrameworkElement fe = sender as FrameworkElement;
            TextBox tbx = fe.FindName("_textMsg") as TextBox;
            tbx.Focus();
            tbx.SelectionStart = tbx.Text.Length;
            _currentMode = EditorModes.DirectMessage;
            ExpandEditor(sender);
        }

        private void _reTwittBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _ignoreTextChanged = true;
            FrameworkElement fe = sender as FrameworkElement;
            TextBox tbx = fe.FindName("_textMsg") as TextBox;
            tbx.Focus();
            if (string.IsNullOrEmpty(tbx.Text))
            {
                tbx.Text = string.Format("RT @{0} : {1}", ((IMessage)fe.DataContext).User.ScreenName, ((IMessage)fe.DataContext).Text);
            }
            tbx.SelectionStart = tbx.Text.Length;
            _currentMode = EditorModes.ReTweet;
            ExpandEditor(sender);
            _ignoreTextChanged = false;
        }

        private void ExpandEditor(object sender)
        {
            FrameworkElement fe = sender as FrameworkElement;
            _expandAllSB = GetStoryboard(fe.DataContext, "ExpandAll");
            _lastExpandedMessage = fe.DataContext as IMessage;
            if (_lastExpandedMessageControl != null && _lastExpandedMessageControl != fe)
            {
                _collapseAllSB = GetStoryboard(fe.DataContext, "CollapseAll");
                _lastExpandedMessageControl.BeginStoryboard(_collapseAllSB);
            }
            fe.BeginStoryboard(_expandAllSB);
            _lastExpandedMessageControl = fe;
            myTwitter.GlobalController.Settings.CanRefresh = false;
        }

        private void CollapseEditor(object sender)
        {
            FrameworkElement fe = sender as FrameworkElement;
            _expandAllSB = GetStoryboard(fe.DataContext, "ExpandAll");
            _lastExpandedMessage = fe.DataContext as IMessage;
            if (_lastExpandedMessageControl != null && _lastExpandedMessageControl != fe)
            {
                _collapseAllSB = GetStoryboard(fe.DataContext, "CollapseAll");
                _lastExpandedMessageControl.BeginStoryboard(_collapseAllSB);
            }
            fe.BeginStoryboard(_expandAllSB);
            _lastExpandedMessageControl = fe;
            myTwitter.GlobalController.Settings.CanRefresh = false;
        }

		private void Grid_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
		{            
            FrameworkElement fe = sender as FrameworkElement;
            _expandActionsSB = GetStoryboard(fe.DataContext, "ExpandActions");
            if ((IMessage)fe.DataContext != _lastExpandedMessage)
            {
                fe.BeginStoryboard(_expandActionsSB);
            }
		}

		private void Grid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
		{
            FrameworkElement fe = sender as FrameworkElement;
            _collapseActionsSB = GetStoryboard(fe.DataContext, "CollapseActions");
            if ((IMessage)fe.DataContext != _lastExpandedMessage)
            {
                fe.BeginStoryboard(_collapseActionsSB);
            }
		}

        private Storyboard GetStoryboard(object dataContext, string name)
        {
            IMessageTemplateSelector selector = new IMessageTemplateSelector();
            DataTemplate template = selector.SelectTemplate(dataContext, this) as DataTemplate;
            return template.Resources[name] as Storyboard;
        }

        private void _sendBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            FrameworkElement fe = sender as FrameworkElement;
            TextBox tbx = fe.FindName("_textMsg") as TextBox;
            IMessage message = fe.DataContext as IMessage;
            switch (_currentMode)
            {
                case EditorModes.ReTweet:
                case EditorModes.Reply:
                    GlobalController.Instances.ITwitterProvider.UpdateStatusAsync(tbx.Text, message.ID);
                    break;

                case EditorModes.DirectMessage:
                    IMessage iMessage = fe.DataContext as IMessage;
                    GlobalController.Instances.ITwitterProvider.SendDirectMessage(iMessage.User.ScreenName, tbx.Text);
                    break;
            }

            _lastExpandedMessage = null;
            _lastExpandedMessageControl = null; 
            myTwitter.GlobalController.Settings.CanRefresh = true;
        }        

        private void _cancelBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _lastExpandedMessage = null;
            _lastExpandedMessageControl = null;
            myTwitter.GlobalController.Settings.CanRefresh = true;
        }

		private void ExRichTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
		{
            if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.LeftAlt))
                e.Handled = false;
            else
                e.Handled = true;
		}

		private void _userBt_Click(object sender, System.Windows.RoutedEventArgs e)
		{
            /*IMessage iMessage = ((FrameworkElement)sender).DataContext as IMessage;
            User u = new User();
            ((IBreadcrumbExplorerEntity)u).Name = iMessage.User.Name;
            
            if (UserInfoRequested != null)
                UserInfoRequested(this, u);

            u.Update(null);*/
            if (UserInfoRequested != null)
            {
                IMessage iMessage = ((FrameworkElement)sender).DataContext as IMessage;                
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += (a, b) =>
                    {
                        Relationship r = GlobalController.Instances.ITwitterProvider.GetRelationship(b.Argument as User);
                        b.Result = r;
                    };
                bw.RunWorkerCompleted += (a, b) =>
                    {
                        if (b.Error != null)
                        {
                            LoadingOff();
                            Mouse.OverrideCursor = null;
                            ExceptionsManager.LogException("Sinapse", b.Error, true);
                        }
                        else
                        {
                            if (iMessage.User.StatusesCount > 0)
                            {
                                LoadingOff();
                                Mouse.OverrideCursor = null;
                                iMessage.User.Relationship = b.Result as Relationship;
                                UserInfoRequested(this, iMessage.User);
                            }
                            else // -> Probably a search result
                            {
                                BackgroundWorker bw2 = new BackgroundWorker();
                                bw2.DoWork += (c, d) =>
                                    {
                                        User u = GlobalController.Instances.ITwitterProvider.GetUser(d.Argument.ToString());
                                        d.Result = u;
                                    };
                                bw2.RunWorkerCompleted += (c, d) =>
                                    {
                                        LoadingOff();
                                        Mouse.OverrideCursor = null;

                                        if (d.Error != null)
                                        {
                                            ExceptionsManager.LogException("Sinapse", d.Error, true);
                                        }
                                        else
                                        {
                                            User u = d.Result as User;
                                            u.Relationship = b.Result as Relationship;
                                            UserInfoRequested(this, u);
                                        }
                                    };
                                bw2.RunWorkerAsync(iMessage.User.ScreenName);
                            }
                        }
                    };
                bw.RunWorkerAsync(iMessage.User);
                Mouse.OverrideCursor = Cursors.Wait;
                LoadingOn();
            }
		}

		private void _textMsg_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
		{
            if (_ignoreTextChanged)
                return;

            TextBox _textMsg = sender as TextBox;

            if (e.Changes.Count == 1)
            {
                foreach (TextChange change in e.Changes)
                {
                    string modifiedText = _textMsg.Text.Substring(change.Offset, change.AddedLength);
                    bool isHyperlink = IsHyperlink(modifiedText);
                    if (isHyperlink)
                    {
                        string tinyUrl = TinyUrl.GetTinyUrl(modifiedText);
                        string newText = _textMsg.Text;
                        newText = _textMsg.Text.Replace(modifiedText, tinyUrl);
                        int index = newText.LastIndexOf(tinyUrl) + tinyUrl.Length;
                        _textMsg.Text = newText;
                        _textMsg.SelectionStart = index;
                    }
                }
            }
		}

        private bool IsHyperlink(string word)
        {
            Regex regex = new Regex(@"(https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*");
            Match match = regex.Match(word);
            if (match.Length > 0)
                return true;
            else
                return false;
        }

        private void _translateBt_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            /*FrameworkElement control = ((FrameworkElement)sender);
            var blurBackgroundSB = control.FindResource("BlurBackgroundSB") as Storyboard;
            var wheelsOnSB = control.FindResource("WheelsOn") as Storyboard;
            control.BeginStoryboard(blurBackgroundSB);
            control.BeginStoryboard(wheelsOnSB);
            
            IMessage message = control.DataContext as IMessage;            
            string text = message.Text;
            string from;
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) =>
                {
                    TranslateClient client = new TranslateClient("http://yannalet.com");
                    b.Result = client.TranslateAndDetect(text, System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName, out from);
                    System.Threading.Thread.Sleep(5000);
                };
            bw.RunWorkerCompleted += (a, b) =>
                {
                    if (b.Error != null)
                    {
                        ExceptionsManager.LogException("Sinapse", b.Error, true);
                    }
                    else
                    {
                        ((IMessage)((FrameworkElement)sender).DataContext).Text = b.Result as string;
                    }
                    wheelsOnSB.Stop();
                    wheelsOnSB.Remove(control);
                    
                };
            bw.RunWorkerAsync();*/
            
        }
	}
}